package com.itheima.search.controller;

import com.itheima.search.feign.SkuFeign;
import com.itheima.search.pojo.SkuInfo;
import com.itheima.util.Page;
import com.itheima.util.UrlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
@RequestMapping("/search")
@CrossOrigin
public class SkuController {

    @Autowired
    private SkuFeign skuFeign;

    /**
     * 搜索
     * @param searchMap 搜索条件
     * @param model 页面
     * @return
     */
    @GetMapping(value = "/list")
    public String search(@RequestParam(required = false) Map<String, String> searchMap, Model model) {
        // 调用搜索
        Map<String, Object> resultMap = skuFeign.search(searchMap);
        model.addAttribute("result", resultMap);
        // 搜索条件存储
        model.addAttribute("searchMap", searchMap);
        // 分页数据获取
        Page<SkuInfo> page = new Page<>(
                Long.parseLong(resultMap.get("totalElements").toString()), // 总记录数
                Integer.parseInt(resultMap.get("pageNum").toString()), // 页数
                Integer.parseInt(resultMap.get("pageSize").toString()) // 当前页面显示了多少条数据
        );
        model.addAttribute("page", page);
        // 获取url地址
        String url = url(searchMap);
        model.addAttribute("url", UrlUtils.replateUrlParameter(url,"pageNum"));
        // 去掉排序域与排序类型域的地址
        model.addAttribute
                ("sorturl", UrlUtils.replateUrlParameter(url, "sortRule", "sortField","pageNum"));
        return "search";
    }

    /**
     * url拼装
     * @param searchMap 搜索条件
     * @return
     */
    private String url(Map<String, String> searchMap) {
        String url = "/search/list";
        // 如果输入了对应的条件, 则将对应的条件拼接到url后面
        if (searchMap != null && searchMap.size() > 0) {
            url += "?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                //获取参数名字
                String key = entry.getKey();
                // 将key拼接到url后面
                url += key+"="+entry.getValue()+"&";
            }
            // 去掉&
            url = url.substring(0, url.length()-1);
        }
        return url;
    }
}
